package com.psw.monitor.geserialport.config;

import com.psw.monitor.geserialport.kafka.GEKafkaProducer;
import com.psw.monitor.geserialport.model.SerialPortMessage;
import com.psw.monitor.geserialport.service.MessageReader;
import com.psw.monitor.geserialport.utils.ConvertHexStrAndStrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class SerialPortCallback {

    public static Logger logger = LoggerFactory.getLogger(SerialPortCallback.class);

    public void dataAvailable() {
        byte[] back = SerialPortManager.readSerialPortData();
        String s = ConvertHexStrAndStrUtils.bytesToHexStr(back);

        SerialPortManager.lastUploadTime = System.currentTimeMillis();

        if (!(s.contains("AABB") && s.contains("CCDD"))) {
            return;
        }
        logger.info(s);
        List<String> strs = new ArrayList<>();
        try {
            int lastIndex = -1;
            while (s.indexOf("AABB", lastIndex) >= 0 && s.indexOf("AABB", lastIndex) + 160 <= s.length()) {
                int index = s.indexOf("AABB", lastIndex);
                String str = s.substring(index, index + 160);
                strs.add(str);
                lastIndex = index + 1;
            }
        } catch (Exception e) {
            logger.error("解析失败,源数据为{}",s,e);
        }
        for (String str : strs) {
            try {
                //当前监听器监听到的串口返回数据 back
                SerialPortMessage msg = MessageReader.read(ConvertHexStrAndStrUtils.hexStrToBytes(str));
                GEKafkaProducer.send(msg);
            } catch (Exception e) {
                logger.error("处理失败,{}", s, e);
            }
        }


    }


    public static void main(String[] args) {
        String s = "5B6164765F7265706F72745D206576656E745F747970653A20307830612C20616464725F747970653A203078303030302C20616464723A2037383A2A2A3A2A2A3A2A2A3A37353A66370D0A5B6164765F7265706F72745D2064617461206C656E6774683A2035322C20646174613A2030783933203078373620307831302030783964203078393120307834390D0AAABB8ABE18A6EDDC52748A3E2E660000D8FFFFFF52025F00999847455F43434D0000E1002A01000000000000000001010000000000000000000000008AF0220019746D6FCE333E520BE5662ECCDD0000AABB8ABE18A6EDDC70F295778C6A0000E2FFFFFF02005F00999847455F43434D0000E500060100000000000000000101000000000000000000000000F2DD80D6";
        int lastIndex = -1;
        while (s.indexOf("AABB", lastIndex) > 0) {
            int index = s.indexOf("AABB", lastIndex);
            String str = s.substring(index, index + 160);
            logger.info(str);
            lastIndex = index + 1;
        }
    }
}

